<!--
  * 微信回复用户
-->
<template>
  <a-modal
    :title="titleMap[props.apiType]"
    :width="1000"
    :open="openForm"
    @cancel="onReplyModalClose"
    :maskClosable="false"
    :destroyOnClose="true"
    @ok="onReplySubmit"
  >
    <a-form :model="replyForm" ref="formRef" :rules="rules">
      <group-title class="pb-0.5">基本信息</group-title>
      <a-form-item :label="props.apiType == 'reply' ? '留言内容' : '文字凭证'" name="replyContent">
        <a-textarea v-model:value="replyForm.replyContent" :rows="4" placeholder="请输入内容，限200个汉字" :maxlength="200" />
      </a-form-item>
      <a-form-item label="图片" v-if="props.formSource == 'alimini'">
        <div class="upload-list">
          <div class="upload-item">
            <a-upload
              v-model:fileList="replyForm.replyImages"
              :customRequest="(file) => uploadFunc(file, 'replyImages')"
              :multiple="false"
              :maxCount="4"
              :accept="limitUpload['replyImages'].fileType.toString()"
              :showUploadList="{ showPreviewIcon: true, showRemoveIcon: true }"
              :before-upload="(file, fileList) => beforeUpload(file, fileList, 'replyImages')"
              list-type="picture-card"
            >
              <div v-if="replyForm.replyImages?.length < 4">
                <plus-outlined />
                <div style="margin-top: 8px">上传</div>
              </div>
            </a-upload>
          </div>
        </div>
      </a-form-item>
      <a-form-item label="图片" v-if="props.formSource == 'ali'">
        <a-button type="primary" href="https://b.alipay.com/page/merchant-openplatform/securityCenter">链接</a-button
        ><span>(如果需再次处理，请到登录支付宝商家平台进行处理)</span>
      </a-form-item>
      <template v-if="props.formSource == 'alimini'">
        <group-title class="pb-0.5">协商历史</group-title>
        <AliHistoryList :row-data="historyData" />
      </template>
    </a-form>
    <template #footer>
      <a-space>
        <a-button @click="onReplyModalClose">取消</a-button>
        <a-button type="primary" @click="onReplySubmit">保存</a-button>
      </a-space>
    </template>
  </a-modal>
</template>
<script setup>
  import { reactive, ref, nextTick, computed, watch } from 'vue'
  import { message, Modal, Upload } from 'ant-design-vue'
  import { aliMiniUpload, aliMiniSupplement, aliMiniReply, aliMiniHistory, aliReply } from '/@/api/business/b-merchant/complaintManage'
  import { PlusOutlined } from '@ant-design/icons-vue'
  import { getObjValue, setObjValue, formatToMoney, strToArr } from '/@/utils/common.js'
  import { myUpload } from '/@/utils/myUpload'
  import AliHistoryList from './ali-history-list.vue'
  import OrderList from './order-list.vue'
  import { cloneDeep, isEmpty } from 'lodash-es'
  import { SmartLoading } from '/@/components/framework/smart-loading'
  // ------------------------ 事件 ------------------------

  const formApi = {
    reply: (data) => {
      if (props.formSource == 'alimini') {
        return aliMiniReply(data)
      }
      if (props.formSource == 'ali') {
        return aliReply(data)
      }
    },
    supplement: aliMiniSupplement,
  }
  const titleMap = { reply: '商家留言', supplement: '商家补充凭证' }
  const props = defineProps({
    open: {
      type: Boolean,
      default: false,
    },
    rowData: {
      type: Object,
      default: () => {},
    },
    apiType: {
      type: String,
      default: 'reply', // reply 回复留言 | supplement 补充凭证
    },
    formSource: {
      type: String,
      default: 'alimini', // alimini | ali
    },
  })
  const emit = defineEmits(['update:open', 'ok'])
  const openForm = computed({ get: () => props.open, set: (val) => emit('update:open', val) })

  // 切换是否退款
  function changeIsRefund(e) {
    if (!e.target.value) return
    let value = e.target.value
    if (value == replyForm.value.isRefund) {
      replyForm.value.isRefund = undefined
    }
    console.log(replyForm.value.isRefund, isEmpty(replyForm.value.isRefund))

    // if (replyForm.value.isRefund) _apiType.value = replyForm.value.isRefund ? 'refund' : 'pay'
  }

  // ------------------------ 显示与隐藏 ------------------------
  // 是否显示

  function show(rowData) {
    console.log('show===>', rowData)

    // 初始化查询
    const { complaintNo, merchantId, channelIds } = rowData
    let channelIdArr = strToArr(channelIds)
    if (!complaintNo) return message.error('投诉单号不能为空')
    if (!merchantId) return message.error('投诉商户id不能为空')
    // if (!channelIdArr || channelIdArr.length == 0) return message.error('支付通道id不能为空')
    replyForm.value.complaintId = complaintNo
    replyForm.value.merchantId = merchantId //'02VA2P2J02E57' //
    // replyForm.value.channelId = channelIdArr[0] //'02TD361I30DND' //

    if (props.formSource == 'alimini') {
      getDetail()
    }
  }

  // 回复用户弹窗相关
  const infoForm = {
    complaintId: undefined, //投诉单id
    isRefund: undefined, //是否退款

    merchantId: null, //商户id
    channelId: null, //通道id
    replyContent: '', //回复内容
    replyImages: [], //回复图片列表
  }
  const replyForm = ref(cloneDeep(infoForm))

  const formRef = ref()
  const rules = ref({
    replyContent: [
      {
        required: true,
        message: '请输入回复内容',
        trigger: 'blur',
      },
    ],
  })
  // 提交回复用户
  async function onReplySubmit() {
    console.log('onReplySubmit', replyForm.value)

    formRef.value.validate().then(async () => {
      const { complaintId, merchantId, replyContent, replyImages } = cloneDeep(replyForm.value)
      let data = {}
      SmartLoading.show()
      try {
        data = {
          complaintId,
          merchantId,
          replyContent,
          replyImages: replyImages?.map((item) => item.response.data).toString(),
        }
        let res = await formApi[props.apiType](data)
        if (res.code === 200) {
          message.success('回复成功')
          emit('ok')
          onReplyModalClose()
        }
      } catch (error) {
        console.log(error)
        // message.error(error)
      }
      SmartLoading.hide()
    })
  }

  const limitUpload = {
    responseImages: {
      fileType: ['.jpg', '.BMP', '.png', '.jpeg', '.pdf'],
      fileSize: 2,
    },
    replyImages: {
      fileType: ['.jpg', '.BMP', '.png', '.jpeg', '.pdf'],
      fileSize: 2,
    },
  }
  // 上传前拦截
  const beforeUpload = (file, fileList, field) => {
    // 校检文件类型
    if (limitUpload[field].fileType.length) {
      const fileExt = file.name.substring(file.name.lastIndexOf('.')).toLowerCase()
      const isTypeOk = limitUpload[field].fileType.includes(fileExt)
      if (!isTypeOk) {
        message.warning(`文件格式不正确, 请上传${limitUpload[field].fileType.toString().replace(/\./g, '').replace(/,/g, '、')}格式文件!`)
        return false || Upload.LIST_IGNORE
      }
    }

    // 校检文件大小
    if (limitUpload[field].fileSize) {
      const isLt = file.size / 1024 / 1024 < limitUpload[field].fileSize
      if (!isLt) {
        message.warning(`上传文件大小不能超过 ${limitUpload[field].fileSize} MB!`)
        return false || Upload.LIST_IGNORE
      }
    }

    return true
  }

  // 上传文件自定义的方法
  const uploadFunc = async (file, fieldName) => {
    // let formData = new FormData()
    // formData.append('file', file.file)
    // try {
    //   const res = await aliMiniUpload(formData)
    //   console.log('微信上传res===>', res)
    //   // if (res.code === 200 && res.data) {
    //   //   fileList.value.push(res.data)
    //   // }
    // } catch (error) {
    //   proxy.$modal.msgError(error)
    // }
    const response = await myUpload(file)

    if (response?.res?.url) {
      aliMiniUpload({
        fileUrl: response?.res?.url,
        fileName: response?.res?.fileName,
        merchantId: props.rowData.merchantId,
      })
    }
  }

  function onReplyModalClose() {
    replyForm.value = cloneDeep(infoForm)
    openForm.value = false
    nextTick(() => {
      formRef.value?.clearValidate()
    })
  }

  /* 获取详情 */
  const historyData = ref([])
  async function getDetail() {
    const { complaintId, merchantId } = cloneDeep(replyForm.value)
    try {
      let res = await aliMiniHistory({ complaintId, merchantId })
      historyData.value = res.data.replyDetailInfos
    } catch (error) {
      console.log(error)
    }
  }
  /* 获取详情 */

  defineExpose({
    show,
  })
  watch(
    [() => props.rowData, () => props.open],
    (val) => {
      if (props.open && props.rowData) {
        show(val[0])
      }
    },
    { immediate: true },
  )
</script>
